package com.lwlk.zdk.controller.Task;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lwlk.zdk.annotation.MyLog;
import com.lwlk.zdk.enums.RetCode;
import com.lwlk.zdk.mapper.pw.pwCheckTheDutyMessageMapper;
import com.lwlk.zdk.mapper.pw.pwUserMapper;
import com.lwlk.zdk.mapper.sys.sysEnterpriseMapper;
import com.lwlk.zdk.mapper.sys.sysUserMapper;
import com.lwlk.zdk.mapper.task.pwTaskMapper;
import com.lwlk.zdk.model.CommonUser;
import com.lwlk.zdk.model.pw.pwCheckTheDutyMessage;
import com.lwlk.zdk.model.task.pwTask;
import com.lwlk.zdk.service.PostService.impl.PostMessageServiceImpl;
import com.lwlk.zdk.service.Task.TaskService;
import com.lwlk.zdk.service.Task.TimeService;
import com.lwlk.zdk.service.Task.impl.TaskServiceImpl;
import com.lwlk.zdk.util.*;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;


@RestController
@Transactional
@RequestMapping(value = "/Task")
public class TaskController {

    @Autowired
    TaskService taskService;
    @Autowired
    TimeService timeService;
    @Autowired
    private PostMessageServiceImpl PostMessageServiceImpl;
    @Autowired
    private sysUserMapper sysUserMapper;
    @Autowired
    private sysEnterpriseMapper sysEnterpriseMapper;
    @Autowired
    private TaskServiceImpl taskServices;
    @Autowired
    private pwTaskMapper pwTaskMapper;
    @Autowired
    pwUserMapper pwUserMapper;

    //=======自动查岗(添加)=============
    @ApiOperation(value = "添加自动查岗信息")
    @MyLog(value = "添加自动查岗信息")  //这里添加了AOP的自定义注解
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Response check(@RequestBody pwTask pwTask, HttpServletRequest request) {
        Response response = new Response();
        try {
            Boolean flag= listerUtil.getRoleType(request);
            if (flag==false){
                response.setCode(RetCode.ACCOUNT_EXIST);
                response.setMsg("此账号为监管员账号,不可进行操作");
                return response;
            }
            String UUID= UUIDUtils.getUUID();
            pwTask.setUUID(UUID);
            int i = taskService.insertBach(pwTask);
            //获取到要查岗的平台id(或企业id)
            pwTask p = this.taskServices.selectAll(pwTask.getId());
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            Date now = new Date();//当前时间
            SimpleDateFormat ds = new SimpleDateFormat("yyyy-MM-dd ");
            Calendar calendar;
            Date executeTime=df.parse(ds.format(now)+" "+p.getCheckTime());//执行时间
           if (p.getAssessPeriod().equals("周")){//定时任务以周为定时
               calendar = Calendar.getInstance();
               String week;
               week = calendar.get(calendar.DAY_OF_WEEK) - 1 + "";//当前星期
               if ("0".equals(week)) {
                   week = "7";
               }
               if (p.getPeriodPeriod()==Integer.parseInt(week)){//如果是从当天开始
                   if (now.before(executeTime)){//如果执行时间在当前时间之后
                       timeService.CreateCheckTime(executeTime,pwTask.getId());
                   }else if (now.after(executeTime)){//如果执行时间在当前时间之前,将执行时间推迟到下周的执行时间
                       Calendar c = Calendar.getInstance();
                       c.setTime(executeTime);
                       c.add(Calendar.DAY_OF_MONTH, 7);//推迟到下周的执行日期
                       timeService.CreateCheckTime(c.getTime(),pwTask.getId());
                   }
               }
               else if(p.getPeriodPeriod()>Integer.parseInt(week)){//如果执行星期大于当前星期
                   Integer num=p.getPeriodPeriod()-Integer.parseInt(week);
                   Calendar c = Calendar.getInstance();
                   c.setTime(executeTime);
                   c.add(Calendar.DAY_OF_MONTH, num);//延长到这周的执行日期
                   timeService.CreateCheckTime(c.getTime(),pwTask.getId());
               }
               else if (p.getPeriodPeriod()<Integer.parseInt(week)){//如果执行星期小于当前星期
                   //每周共七天,减去当前日期,加上执行的日期,就是最终的日期
                   Integer num=7-Integer.parseInt(week)+p.getPeriodPeriod();
                   Calendar c = Calendar.getInstance();
                   c.setTime(executeTime);
                   c.add(Calendar.DAY_OF_MONTH, num);//延长到这周的执行日期
                   timeService.CreateCheckTime(c.getTime(),pwTask.getId());
               }
           }
           if (p.getAssessPeriod().equals("月")) {//定时任务以月为定时任务
               calendar = Calendar.getInstance();
               //Integer month;
               //month = calendar.get(calendar.MONTH) + 1;//当前月份
               Integer day;//几号
               day = calendar.get(calendar.DAY_OF_MONTH);
               Integer num = p.getPeriodPeriod() - day;
               if (p.getPeriodPeriod() > day && p.getPeriodPeriod() <= 28) {//如果执行大于今天的时间 并且小于31天
                   Calendar c = Calendar.getInstance();
                   c.setTime(executeTime);
                   c.add(Calendar.DAY_OF_MONTH, num);//延长到这个月的执行日期
                   timeService.CreateCheckTime(c.getTime(), pwTask.getId());
               } else if (p.getPeriodPeriod() < day) {//如果执行时间小于今天时间,就让下月执行
                   Calendar c = Calendar.getInstance();
                   c.setTime(executeTime);
                   c.add(Calendar.MONTH, 1);//延长到下个月的执行日期
                   timeService.CreateCheckTime(c.getTime(), pwTask.getId());
               } else if(p.getPeriodPeriod()==day){//如果执行时间就在当天
                   if (executeTime.before(now)){//如果执行时间在当天时间之前,延长到下个月执行
                       Calendar c = Calendar.getInstance();
                       c.setTime(executeTime);
                       c.add(Calendar.DAY_OF_MONTH, 1);//延长到下个月的执行日期
                       timeService.CreateCheckTime(c.getTime(), pwTask.getId());
                   }else if (executeTime.after(now)){
                       Calendar c = Calendar.getInstance();
                       c.setTime(executeTime);
                       c.add(Calendar.DAY_OF_MONTH, 0);//当月的执行日期
                       timeService.CreateCheckTime(c.getTime(), pwTask.getId());
                   }

               }
           }
            if (p.getAssessPeriod().equals("日")){
                Calendar  c;
                c=Calendar.getInstance();
                if (executeTime.before(now)){//如果执行时间在当前时间之前,明天执行
                    c.setTime(executeTime);
                    c.add(Calendar.DAY_OF_MONTH, 1);//明日的执行日期
                    timeService.CreateCheckTime(c.getTime(), pwTask.getId());
                }else if (executeTime.after(now)){//如果执行时间在当前时间之后,操作执行时间
                    timeService.CreateCheckTime(executeTime, pwTask.getId());
                }
            }
            response.setCode(RetCode.SUCCESS);
            response.setMsg("执行成功");
            response.setData(i);
        }catch (Exception e){
            e.printStackTrace();
        }
        return response;
    }


    @ApiOperation(value = "展示自动查岗信息")
    @RequestMapping(value = "/showTaskMessage",method = RequestMethod.GET)
    public LayuiTablePagingResult showTaskMessage(Integer page,Integer size,String assessPeriod,String issueType,String assessObject,Integer platformIds,Integer uId){
        LayuiTablePagingResult result=null;
        try {
            PageHelper.startPage(page,size);
            List<Map<String,Object>>taskList=taskService.selectCondition(assessPeriod,issueType,assessObject,platformIds,uId);
            for (int i = 0; i < taskList.size(); i++) {
                Map map=taskList.get(i);
                String week=null;
                String period=String.valueOf(taskList.get(i).get("periodPeriod"));
                if (String.valueOf(taskList.get(i).get("assessPeriod")).equals("周")){
                    String periodPeriod=null;
                     week=period.equals("0")?"周一":period.equals("1")?"周二":period.equals("2")?"周三":period.equals("3")?"周四":period.equals("4")?"周五":period.equals("5")?"周六":period.equals("6")?"周日":null;
                    periodPeriod=String.valueOf(Integer.parseInt(period)+1);
                    map.put("periodPeriod",periodPeriod);
                    map.put("period",week);
                }else {
                    map.put("periodPeriod",period);
                    if (period.equals("null")){
                        map.put("period","每日");
                    }else {
                        map.put("period",period);
                    }

                }
            }
            PageInfo pageInfo=new PageInfo<>(taskList);
            result = new LayuiTablePagingResult();
            result.setCode(RetCode.SUCCESS.getCode());
            result.setMsg(RetCode.SUCCESS.getMsg());
            result.setCount(pageInfo.getTotal());
            result.setData(pageInfo.getList());
            Long totalPages = pageInfo.getTotal() / size;
            if (pageInfo.getTotal() % size != 0){
                totalPages ++;
            }
            result.setTotalPages(totalPages);

        }catch (Exception e){
            e.printStackTrace();
        }
        return result;

    }

    @ApiOperation(value = "删除自动查岗信息")
    @RequestMapping(value = "/delete",method = RequestMethod.POST)
    public Response getDelete(Integer id,HttpServletRequest request){
        Response response=new Response();
        Boolean flag=listerUtil.getRoleType(request);
        if (flag==false){
            response.setCode(RetCode.ACCOUNT_EXIST);
            response.setMsg("此账号为监管员账号,不可进行操作");
            return response;
        }

        Integer i=pwTaskMapper.delete(id);
        response.setCode(RetCode.SUCCESS);
        response.setMsg("执行成功");
        response.setData(i);
        return response;
    }

    @ApiOperation(value = "自动查岗详情")
    @RequestMapping(value = "/details",method = RequestMethod.GET)
    public Response getDetails(Integer id){
        Response response=new Response();
        List<Map<String,Object>>taskDetails=pwTaskMapper.selectDetails(id);
        response.setData(taskDetails);
        response.setCode(RetCode.SUCCESS);
        response.setMsg("执行成功");
        return response;
    }



    @ApiOperation(value = "修改自动查岗信息")
    @MyLog(value = "修改自动查岗信息")  //这里添加了AOP的自定义注解
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public Response updateCheck(@RequestBody pwTask pwTask,HttpServletRequest request) {
        Response response = new Response();
        try {
            Boolean flag=listerUtil.getRoleType(request);
            if (flag==false){
                response.setCode(RetCode.ACCOUNT_EXIST);
                response.setMsg("此账号为监管员账号,不可进行操作");
                return response;
            }
            String UUID= UUIDUtils.getUUID();
            pwTask.setUUID(UUID);
            int i = taskService.update(pwTask);
            //获取到要查岗的平台id(或企业id)
            pwTask p = this.taskServices.selectAll(pwTask.getId());
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            Date now = new Date();//当前时间
            SimpleDateFormat ds = new SimpleDateFormat("yyyy-MM-dd ");
            Calendar calendar;
            Date executeTime=df.parse(ds.format(now)+" "+p.getCheckTime());//执行时间
            if (p.getAssessPeriod().equals("周")){//定时任务以周为定时
                calendar = Calendar.getInstance();
                String week;
                week = calendar.get(calendar.DAY_OF_WEEK) - 1 + "";//当前星期
                if ("0".equals(week)) {
                    week = "7";
                }
                if (p.getPeriodPeriod()==Integer.parseInt(week)){//如果是从当天开始
                    if (now.before(executeTime)){//如果执行时间在当前时间之后
                        timeService.CreateCheckTime(executeTime,pwTask.getId());
                    }else if (now.after(executeTime)){//如果执行时间在当前时间之前,将执行时间推迟到下周的执行时间
                        Calendar c = Calendar.getInstance();
                        c.setTime(executeTime);
                        c.add(Calendar.DAY_OF_MONTH, 7);//推迟到下周的执行日期
                        timeService.updateOnInspectionTime(c.getTime(),pwTask.getId());
                    }
                }
                else if(p.getPeriodPeriod()>Integer.parseInt(week)){//如果执行星期大于当前星期
                    Integer num=p.getPeriodPeriod()-Integer.parseInt(week);
                    Calendar c = Calendar.getInstance();
                    c.setTime(executeTime);
                    c.add(Calendar.DAY_OF_MONTH, num);//延长到这周的执行日期
                    timeService.updateOnInspectionTime(c.getTime(),pwTask.getId());
                }
                else if (p.getPeriodPeriod()<Integer.parseInt(week)){//如果执行星期小于当前星期
                    //每周共七天,减去当前日期,加上执行的日期,就是最终的日期
                    Integer num=7-Integer.parseInt(week)+p.getPeriodPeriod();
                    Calendar c = Calendar.getInstance();
                    c.setTime(executeTime);
                    c.add(Calendar.DAY_OF_MONTH, num);//延长到这周的执行日期
                    timeService.updateOnInspectionTime(c.getTime(),pwTask.getId());
                }
            }
            if (p.getAssessPeriod().equals("月")) {//定时任务以月为定时任务
                calendar = Calendar.getInstance();
                //Integer month;
                //month = calendar.get(calendar.MONTH) + 1;//当前月份
                Integer day;//几号
                day = calendar.get(calendar.DAY_OF_MONTH);
                Integer num = p.getPeriodPeriod() - day;
                if (p.getPeriodPeriod() > day && p.getPeriodPeriod() <= 28) {//如果执行大于今天的时间 并且小于31天
                    Calendar c = Calendar.getInstance();
                    c.setTime(executeTime);
                    c.add(Calendar.DAY_OF_MONTH, num);//延长到这个月的执行日期
                    timeService.updateOnInspectionTime(c.getTime(), pwTask.getId());
                } else if (p.getPeriodPeriod() < day) {//如果执行时间小于今天时间,就让下月执行
                    Calendar c = Calendar.getInstance();
                    c.setTime(executeTime);
                    c.add(Calendar.MONTH, 1);//延长到下个月的执行日期
                    timeService.updateOnInspectionTime(c.getTime(), pwTask.getId());
                } else if(p.getPeriodPeriod()==day){//如果执行时间就在当天
                    if (executeTime.before(now)){//如果执行时间在当天时间之前,延长到下个月执行
                        Calendar c = Calendar.getInstance();
                        c.setTime(executeTime);
                        c.add(Calendar.DAY_OF_MONTH, 1);//延长到下个月的执行日期
                        timeService.updateOnInspectionTime(c.getTime(), pwTask.getId());
                    }else if (executeTime.after(now)){
                        Calendar c = Calendar.getInstance();
                        c.setTime(executeTime);
                        c.add(Calendar.DAY_OF_MONTH, 0);//当月的执行日期
                        timeService.updateOnInspectionTime(c.getTime(), pwTask.getId());
                    }

                }
            }
            if (p.getAssessPeriod().equals("日")){
                Calendar  c;
                c=Calendar.getInstance();
                if (executeTime.before(now)){//如果执行时间在当前时间之前,明天执行
                    c.setTime(executeTime);
                    c.add(Calendar.DAY_OF_MONTH, 1);//明日的执行日期
                    timeService.updateOnInspectionTime(c.getTime(), pwTask.getId());
                }else if (executeTime.after(now)){//如果执行时间在当前时间之后,操作执行时间
                    timeService.updateOnInspectionTime(executeTime, pwTask.getId());
                }
            }
            response.setCode(RetCode.SUCCESS);
            response.setMsg("执行成功");
            response.setData(i);
        }catch (Exception e){
            e.printStackTrace();
        }
        return response;
    }


}
